
//pauls function.  Works Great!
function validDate(date){
	//var for required element error message.
	var date_message = " <span id='error_message'>Must be a valid date.</span>";
	
	//removes error messages from previous validation.
	$(".textbox_error").removeClass();
	$("span[id='error_message']").remove();
	$("#error").hide();
	
	//pauls date validator in action with jquery.
	var validator = new pdv();
	if (date.value.length > 0) {
		if (validator.IsSQLServerDate(date.value)){
			date.value = validator.DisplayDate(date.value, 'mm/dd/yyyy');			
		}else{		
			$("#error").show();
			$("#" + date.id + " ~ img").after(date_message);
			$("#" + date.id).addClass('textbox_error');	
		}
	}	
}


var validateElements = function(){
	//sets error count to zero, if greater then zero, some data is not valid
	var error_count = 0;
	
	//var for required element error message.
	var require_message = " <span id='error_message' style='display:block'>Field is required.</span>";
	
	//var for phone number validation.
	var phone_message = " <span id='error_message' style='display:block'>Not a valid number.</span>";
	
	//these fields are require on form.
	var required_fields = [];
	
	//these fields are phone numbers.
	var phone_fields = [];
	
	//removes error messages from previous validation.
	$(".textbox_error").removeClass();
	$("span[id='error_message']").remove();
	$("#error").hide();
	
	//if fields in the required_fields variable are empty this error is triggered.
	$.map(required_fields,function(field){
		if( !$("#" + field).val() )	{
			error_count++;
			$("#error").show();
			$("#" + field).after(require_message);
			$("#" + field).addClass('textbox_error');
		}
	});
		
	//if no errors in validation, well... the data is valid!
	if(error_count){return false;}else{return true;}
};


function bindElements(){	
	
	$("#save_intake").hide();
	
	//bind copy address button to copy address to mailing address when clicked.
	$("#copy_address").click(function(){
		$("#MailingAddress").val( $("#Address").val() );
		$("#MailingAptSpaceNo").val( $("#AptSpaceNo").val() );
		$("#MailingCity").val( $("#City").val() );
		$("#MailingState").val( $("#State").val() );
		$("#MailingZip").val( $("#Zip").val() );
	});
	
	//make meal_date textbox a datepicker
	$("#DateOfContact, #dob, #ElderSignatureDate:not(input[type='hidden']), #StaffSignatureDate:not(input[type='hidden']), #SupervisorSignatureDate:not(input[type='hidden'])").datepicker({ 
		dateFormat: 'mm/dd/yy', changeYear: true, changeMonth: true, yearRange: '1900:2010', autoSize: true,
		prevText: 'Earlier', nextText: 'Later', showOn: 'button', 
		buttonImage: '/CFIDE/scripts/ajax/resources/cf/images/DateChooser.png', buttonImageOnly: true,
		onClose: function(dateText, inst) { $(this).focus()}
	});
	
	//binds IADL textboxes to total up entered values.


	//this binds 'add' button's click event to trigger form validation before sending to database.  
	$("#save_intake").bind("click", function(){
		if ( validateElements() ){
			if( $("#elder option:selected").val() == '-1' ){
				$("#myform").attr({'action': 'api.cfm?api=add_intake', 'method':'POST'});
				$("#myform").submit();
			}else{
				$("#myform").attr({'action': 'api.cfm?api=edit_intake&id=' + $("#elder option:selected").val(), 'method':'POST'});
				$("#myform").submit();	
			}
		}
	});
	
	
	//this binds 'add' button's click event to trigger form validation before sending to database.  
	$("#update_intake").bind("click", function(){
		if ( validateElements() ){
			if( $("#elder option:selected").val() != '-1' ){
				$("#myform").attr({'action': 'api.cfm?api=edit_intake&id=' + $("#elder option:selected").val(), 'method':'POST'});
				$("#myform").submit();
			}
		}
	});
	
	
	//this binds 'add' button's click event to trigger form validation before sending to database.  
	$("#delete_intake").bind("click", function(){
		if ( validateElements() ){
			if( $("#elder option:selected").val() != '-1' ){
				$("#myform").attr({'action': 'api.cfm?api=delete_intake_by_id&id=' + 
					$("#elder option:selected").val(), 'method':'POST'});
				$("#myform").submit();
			}
		}
	});
	
	//pageination binding.  page links at the top of the page need to change page, and class.
	$("#page1, #page2, #page3, #page4").click(function(e){
		var pages = ['page1', 'page2', 'page3', 'page4'];
		var page_divs = { page1:'page_1', page2:'page_2', page3:'page_3', page4:'page_4' };
		var clicked = this;
		
		//finds links not clicked on.
		var not_current = $.map(['page1', 'page2', 'page3', 'page4'], function(n){	
			if( n != $(clicked).attr('id') ) {return n} 
		});
		
		//loops over list to add "current" class to clicked page
		$.map(['page1', 'page2', 'page3', 'page4'], function(n){ 
			$("#" + n).addClass('current'); 
			$("#" + n + "_bottom").addClass('current');$("#" + page_divs[n]).show();
		});
		
		//loops over list to remove "current" class from pages that are current
		$.map(not_current, function(n){ 
			$("#" + n).removeClass('current');
			$("#" + n+ "_bottom").removeClass('current');$("#" + page_divs[n]).hide();
		});
		return false;
	});
	
	//pageination binding.  page links at the top of the page need to change page, and class.
	$("#page1_bottom, #page2_bottom, #page3_bottom, #page4_bottom").click(function(e){
		var page_divs = { page1_bottom:'page_1', page2_bottom:'page_2', page3_bottom:'page_3', page4_bottom:'page_4' };
		var clicked = this;
		
		//finds links not clicked on.
		var not_current = $.map(['page1_bottom', 'page2_bottom', 'page3_bottom', 'page4_bottom'], function(n){	
			if( n != $(clicked).attr('id') ) {return n} 
		});
		
		//loops over list to add "current" class to clicked page
		$.map(['page1_bottom', 'page2_bottom', 'page3_bottom', 'page4_bottom'], function(n){ 
			$("#" + n).addClass('current'); 
			$("#" + n.split("_")[0]).addClass('current'); 
			$("#" + page_divs[n]).show();
		});
		
		//loops over list to remove "current" class from pages that are current
		$.map(not_current, function(n){ 
			$("#" + n).removeClass('current'); 
			$("#" + n.split("_")[0]).removeClass('current'); 
			$("#" + page_divs[n]).hide()
		});
		return false;
	});
	//pageination binding.  page links at the top of the page need to change page, and class.		
	
	//binds change event to getDataById.  This is to populate form data.
	$("#elder").bind("change", function(){
		loadElder();		
	});
	
	//bind checked boxes
	if( $("#elder option:selected").val() == -1){
		$("#new_intake").attr('checked', true);
		$("#edit_intake").attr('checked', false);
		$("#save_intake").show();
	}
	
	//bind useless checkboxes the customer can't live without.  Checking a checkbox will change the elder dropdown 
	//binds click event to uncheck the other checkbox.
	$("#new_intake").click(function(){
		$("#elder").val(-1).attr('selected');
		$("#ElderID").val( $("#elder option:selected").val() );
		$("#save_intake").show();
		$("#edit_intake").attr('checked', false);
		window.location.href="intake.cfm?ElderID=" + $("#elder option:selected").val();		
	});
	
	//binds click event to uncheck the other checkbox.
	$("#edit_intake").click(function(){
		$("#save_intake").show();
		$("#new_intake").attr('checked', false);
	});
	
	if ( $("#edit_intake").attr('checked') ){
		$("#save_intake").show();
		$("#new_intake").attr('checked', false);
	}	
		
	//binds elder_search focus out to load selected elder
	$("#elder_search").focusout(function(){		
		if($(this).val().split(" - ")[1]){
			var x = $(this).val().split(" - ")
			$(this).val(x[0]);
			$("#elder").val(x[1]).attr('selected');
			loadElder();
		}
	});

	
	//bind none Elder phone numbers to automaticly format phone numbers
	$("#HomePhone, #LegalRepHomePhone, #LegalRepCellPhone, #EmergencyContactHomePhone, " + 
	 "#EmergencyContactCellPhone, #EmergencyContactHomePhone2, #EmergencyContactCellPhone2, " + 
	 "#ProviderPhoneNumber, #cg_Phone, #UsuallyAssistsPhone1, #UsuallyAssistsPhone2, " + 
	 "#UsuallyAssistsPhone3, #UsuallyAssistsPhone4").bind("blur", function(){		
		$(this).removeClass('textbox_error');
		var phone = $(this).val();
		var validPhone = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/; 
		if(phone.length == 10){
			$(this).val("");
			var area_code = phone.substr(0, 3);
			var preffix = phone.substr(3, 3);
			var suffix = phone.substr(6);
			$(this).val("(" + area_code + ") " + preffix + " - " + suffix);
		}else if(phone.length == 7){
			$(this).val("");
			var preffix = phone.substr(0, 3);
			var suffix = phone.substr(3);
			$(this).val("(907) " + preffix + " - " + suffix);
		}else if( phone.match(validPhone) ){
			return false;			   
		}else{
			$(this).val("");
			$(this).addClass('textbox_error').val("");
			return false;
		}		
	});
	
	bindCaregiverLinks();
	
	$("#add_caregiver").click(function(){
		$(this).addClass("hidden");
		$("#delete_caregiver").addClass("hidden");
		$("#save_caregiver").removeClass("hidden");
		$("#caregiver").removeClass("hidden");
		refreshCaregiverForm();		
		return false;
	});
	
	$("#save_caregiver").click(function(){
		$(this).addClass("hidden");		
		var form_dict = {};
		form_dict['ElderID'] = $("#ElderID").val();
		form_dict['cg_LastName'] = $("#cg_LastName").val();
		form_dict['cg_FirstName'] = $("#cg_FirstName").val();
		form_dict['cg_Address'] = $("#cg_Address").val();
		form_dict['cg_City'] = $("#cg_City").val();
		form_dict['cg_State'] = $("#cg_State").val();
		form_dict['cg_Zip'] = $("#cg_Zip").val();
		form_dict['cg_Phone'] = $("#cg_Phone").val();
		form_dict['cg_RelationshiptoElder'] = $("#cg_RelationshiptoElder").val();
		form_dict['cg_EmploymentStatus'] = $("#cg_EmploymentStatus").val();
		form_dict['cg_HouseholdStatus'] = $("#cg_HouseholdStatus").val();
		form_dict['cg_Contact'] = $("#cg_Contact").val();
		form_dict['cg_ContactFrequency'] = $("#cg_ContactFrequency").val();
		submitCargiver(form_dict, "add_caregivers");
		$("#add_caregiver").removeClass("hidden");
		$("#caregiver").addClass("hidden");
		refreshCaregiverForm();
		return false;
	});
	
	$("#delete_caregiver").click(function(){
		$(this).addClass("hidden");
		$("#add_caregiver").removeClass("hidden");
		var form_dict = {};
		submitForm(form_dict, "delete_caregiver_by_id", $("#cg_CareGiverID").val());
		$("#cg_" + $("#cg_CareGiverID").val()).remove();
		$("#delete_caregiver").addClass("hidden");
		$("#save_caregiver").addClass("hidden");
		$("#caregiver").addClass("hidden");	
        showCaregiverList();
		bindCaregiverLinks();	
		refreshCaregiverForm();
		return false;
	});

}

function showCaregiverList(){
	
	$("#caregivers_list").text('');
	
	var caregivers = getDataById('get_elders_caregivers', $("#ElderID").val() ).DATA;
	$.each(caregivers['CAREGIVERID'], function(i, n){
		$("#caregivers_list").append("&nbsp;&nbsp;<a href='#' id='cg_" + caregivers['CAREGIVERID'][i] + "'>" + 
		caregivers['LASTNAME'][i] + ", " + caregivers['FIRSTNAME'][i] + "</a>");
	});
    
    bindCaregiverLinks();

}


function bindCaregiverLinks(){
	//bind caregiver link
	$("a[id^='cg_']").bind("click", function(){
		$("#caregiver").removeClass("hidden");
		var caregiver = getDataById("get_caregiver_by_id", this.id.split("_")[1]).DATA;
		$("#delete_caregiver").removeClass('hidden');
		$("#save_caregiver").removeClass('hidden');	
		$("#add_caregiver").addClass('hidden');
		$("#cg_CareGiverID").val(caregiver['CAREGIVERID']);
		$("#cg_LastName").val(caregiver['LASTNAME']);
		$("#cg_FirstName").val(caregiver['FIRSTNAME']);
		$("#cg_Address").val(caregiver['ADDRESS']);
		$("#cg_City").val(caregiver['CITY']);
		$("#cg_State").val(caregiver['STATE']);
		$("#cg_Zip").val(caregiver['ZIP']);
		$("#cg_Phone").val(caregiver['PHONE']);
		$("#cg_RelationshiptoElder").val(caregiver['RELATIONSHIPTOELDER']);
		$("#cg_EmploymentStatus").val(caregiver['EMPLOYMENTSTATUS']);
		$("#cg_HouseholdStatus").val(caregiver['HOUSEHOLDSTATUS']);
		$("#cg_Contact").val(caregiver['CONTACT']);
		$("#cg_ContactFrequency").val(caregiver['CONTACTFREQUENCY']);	
		return false;
	});			
}

function refreshCaregiverForm(){
	var element_list = [
		'cg_LastName','cg_FirstName','cg_Address','cg_City','cg_State','cg_Zip',
		'cg_Phone','cg_RelationshiptoElder','cg_EmploymentStatus','cg_Householdtatus',
		'cg_Contact','cg_ContactFrequency', "cg_CareGiverID"
	];
	
	$.map(element_list,function(n){ $("#" + n).val(""); });		
}


function loadElder(){
	//takes value of selected option in the elder dropdown and passes it to the function that fills the form.
	if($("#elder option:selected").val() != -1){			
		//setting session variable that holds current elder selected
		window.location.href="intake.cfm?ElderID=" + $("#elder option:selected").val();
		var session_elder_id = new sse();
		session_elder_id.funcSetSessionElderID( $("#elder option:selected").val() );
	}
	else{
		window.location.href="intake.cfm?ElderID=-1";
		var session_elder_id = new sse();
		session_elder_id.funcSetSessionElderID( $("#elder option:selected").val() );
		clearElements();
		$('#LastName').focus();
	}	
}



function clearElements(){
	
	//reset all textboxes
	$(":input:not(input[type='button']):not(input[type='hidden']):not(input[id='date_of_contact'])" + 
		":not(input[id='elder_search']):not(select[id='elder']):not(input[id='sign_date'])").val("");
	
	//This sets the new checkbox to checked if the elder is new
	if( $("#elder option:selected").val() == -1 ){
		$("#new_intake").attr('checked', true)
	}
	
	//reset idal textboxes to zero
	$("#iadl :input:not(input[id$='_manage'])").val(0);
	
	//reset date of contact to today's date
	$("#date_of_contact").val($('#sign_date').val());
	
}



//ajax POST to add to database.
function submitCargiver(obj, api, id, successFunc, completeFunc, errorFunc){    
    var api_url = "api.cfm?api=" + api + ( (id) ? "&id=" + id : "" );
    $.ajax({
        type:'POST', url:api_url, dataType: 'json', async: true, data: obj,
        success: function(json) {
            var json = json.DATA;
           $("#caregivers_list").append("&nbsp;&nbsp;<a href='#' id='cg_" + json['CAREGIVERID'][0] + "'>" + 
            json['LASTNAME'][0] + ", " + json['FIRSTNAME'][0] + "</a>");
        },
        complete: function(){bindCaregiverLinks()},
        error: function(){errorFunc}
    });
}


//ajax POST to add to database.
function submitForm(obj, api, id, successFunc, completeFunc, errorFunc){	
	var api_url = "api.cfm?api=" + api + ( (id) ? "&id=" + id : "" );
	$.ajax({
		type:'POST', url:api_url, dataType: 'json', async: true, data: obj,
		success: function() {successFunc},
		complete: function(){completeFunc},
		error: function(){errorFunc}
	});
}

//ajax GET to retrive data from database.
var getDataById = function(api, id){
	var data = {};
	var api_url = "api.cfm?api=" + api + ( (id) ? "&id=" + id : "" );
	
	if (id != -1){
		$.ajax({
		type:'GET', url: api_url, dataType: 'json', async: false,
			success: function(json) { data = json; }
		});
	}
	
	return data;
};


$(function(){
	$("#page_1").show();
	$("#page_2, #page_3, #page_4").hide();
	bindElements();
});